package com.java.service.Impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.config.exceptioin.YyghException;
import com.java.config.result.ResultCodeEnum;
import com.java.mapper.ScheduleMapper;
import com.java.model.hosp.BookingRule;
import com.java.model.hosp.Department;
import com.java.model.hosp.Hospital;
import com.java.model.hosp.Schedule;
import com.java.model.vo.BookingScheduleRuleVo;
import com.java.model.vo.ScheduleOrderVo;
import com.java.model.vo.ScheduleQueryVo;
import com.java.repository.ScheduleRespoitory;
import com.java.service.DepartmentService;
import com.java.service.HospitalService;
import com.java.service.ScheduleService;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ScheduleServiceImpl extends ServiceImpl<ScheduleMapper,Schedule> implements ScheduleService {


    @Autowired
    private ScheduleRespoitory scheduleRespoitory;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private HospitalService hospitalService;

    @Autowired
    private DepartmentService departmentService;

    @Override
    public void save(Map<String, Object> paramMap) {
        //map 集合转 对象
        String jsonString = JSONObject.toJSONString(paramMap);
        Schedule schedule = JSONObject.parseObject(jsonString, Schedule.class);

        //根据hoscode 和  hosScheduleId 查询排班信息
        String hoscode = schedule.getHoscode();
        String hosScheduleId = schedule.getHosScheduleId();

        Schedule scheduleExist = scheduleRespoitory.getScheduleByHoscodeAndHosScheduleId(hoscode,hosScheduleId);

        if(scheduleExist!=null){
            //修改
            scheduleExist.setStatus(1);
            scheduleExist.setUpdateTime(new Date());
        }else{
            //保存
            schedule.setStatus(1);
            scheduleRespoitory.save(schedule);
        }
    }

    /**
     *
     * @param pageNum
     * @param pageSize
     * @param scheduleQueryVo
     * @return
     */
    @Override
    public Page findSchedulByPage(int pageNum, int pageSize, ScheduleQueryVo scheduleQueryVo) {
        //分页数据
        Pageable pageable = PageRequest.of(pageNum-1, pageSize);
        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreCase(true);
        //创建实例
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(scheduleQueryVo,schedule);
        schedule.setIsDeleted(0);
        Example<Schedule> example = Example.of(schedule, matcher);

        //条件分页查询
        Page all = scheduleRespoitory.findAll(example,pageable);
        return all;
    }

    /**
     * 删除排班接口
     * @param hoscode
     * @param hosScheduleId
     */
    @Override
    public void remove(String hoscode, String hosScheduleId) {
        Schedule schedule = scheduleRespoitory.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if(schedule!=null){
            scheduleRespoitory.deleteById(schedule.getId());
        }
    }

    /**
     * 获取排班信息
     * @param hoscode
     * @param depcode
     */
    @Override
    public Map<String, Object> getShoduleMap(Integer pageNum, Integer pageSize, String hoscode, String depcode) {
        Map<String, Object> result = new HashMap<>();
        //1、根据医院编号和科室编号查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
        //2、根据工作日workdate进行分组
        Aggregation agg1 =  Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
                .first("workDate").as("workDate")
                //3 统计号源数量
                .count().as("docCount")
                .sum("reservedNumber").as("reservedNumber")
                .sum("availableNumber").as("availableNumber"),
                //排序
                Aggregation.sort(Sort.Direction.DESC,"workDate"),
                //分页
                Aggregation.skip((pageNum-1)*pageSize),
                Aggregation.limit(pageSize)
        );
        //调用方法 最终执行 1、agg 参数对象 2、传入的实体class 3、返回的结果class
        AggregationResults<BookingScheduleRuleVo> bookScheduleRuleVoList =
                mongoTemplate.aggregate(agg1, Schedule.class, BookingScheduleRuleVo.class);

        List<BookingScheduleRuleVo> Results = bookScheduleRuleVoList.getMappedResults();

        Aggregation totalAgg =  Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")


        );
        //分组之后的总记录数
        AggregationResults<BookingScheduleRuleVo> totalAggResults =
                mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
        int total = totalAggResults.getMappedResults().size();

        //根据日期返回星期几
        for (BookingScheduleRuleVo item : bookScheduleRuleVoList){
            Date date = item.getWorkDate();
            String week = dayOfWeek(date);
            item.setDayOfWeek(week);
        }
        //医院的名称
        String hosname = hospitalService.getHosNameByHoscode(hoscode);
        Map<String, Object> map = new HashMap<>();
        map.put("total",total);
        map.put("Results",Results);
        Map<String,Object> baseMap = new HashMap<>();
        baseMap.put("hosname",hosname);
        map.put("baseMap",baseMap);
        System.out.println(map);
        return map;

    }


    @Override
    public List<Schedule> getScheduleDetail(String hoscode,String depcode,String workDate) {
        DateTime dateTime = DateUtil.parse(workDate);
        //从mongodb中查询
        List<Schedule> scheduleList = scheduleRespoitory.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode,depcode,dateTime);

        scheduleList.stream().forEach(item->{
            packShudelDetail(item);
        });

        return scheduleList;
    }

    @Override
    public Map<String,Object> getBookingScheduleRule(int pageNum, int pageSize, String hoscode, String depcode) {
        Map<String, Object> result = new HashMap<>();
        Hospital hospital = hospitalService.getHospital(hoscode);
        if(hospital == null){
            throw new YyghException(ResultCodeEnum.HOSPITAL_OPEN);
        }
        BookingRule bookingRule = hospital.getBookingRule();
        //核心getListDate
        IPage iPage = this.getListDate(pageNum,pageSize,bookingRule);
        //时间
        List<Date> dateList = iPage.getRecords();
        //从MogoDB中查询：根据hoscode depcode 和workeDate得到 可预约科室的剩余预约数
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode).and("workDate").in(dateList);
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate").first("workDate").as("workDate")
                .count().as("docCount")
                .sum("availableNumber").as("availableNumber")
                .sum("reservedNumber").as("reservedNumber")

        );
        //查询、并获取结果
        AggregationResults<BookingScheduleRuleVo> aggregationResults
                = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        //[{workDate:xxx,docCount:xxx,reservedNumber:xxx...},{},{}]
        List<BookingScheduleRuleVo> scheduleRuleVoList = aggregationResults.getMappedResults();
        //list 转 map 集合 {workDate:{docCount:xxx,xxx:xxx}}
        Map<Date, BookingScheduleRuleVo> scheduleVoMap =
                scheduleRuleVoList.stream().collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate, BookingScheduleRuleVo -> BookingScheduleRuleVo));
        //循环
        List bookingScheduleRuleList = new ArrayList();
        for(int i=0,len = dateList.size();i<len;i++){
            Date date = dateList.get(i);
            BookingScheduleRuleVo scheduleRuleVo = scheduleVoMap.get(date);
            //如果规则为null 说明那天无号
            if(scheduleRuleVo == null){
                scheduleRuleVo = new BookingScheduleRuleVo();
                scheduleRuleVo.setDocCount(0);
                scheduleRuleVo.setAvailableNumber(-1);
            }
            //如果不为Null
            scheduleRuleVo.setWorkDate(date);
            scheduleRuleVo.setWorkDateMd(date);
            //得到当前的对应日期
            String week = dayOfWeek(date);
            //最后一页最后一条记录为即将预约 0：正常 1：即将放号 -1：当天停止挂号
            if(i == len -1 && pageNum == iPage.getPages()){
                scheduleRuleVo.setStatus(1);
            }else{
                scheduleRuleVo.setStatus(0);
            }
            //当天预约如果过了停号时间
            if(i == 0 && pageNum == 1){
                String dateTimeString = new org.joda.time.DateTime(new Date()).toString("yyyy-MM-dd") + " " + bookingRule.getStopTime();
                org.joda.time.DateTime stopTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
                if(stopTime.isBeforeNow()){
                    //停止预约
                    scheduleRuleVo.setStatus(-1);
                }
            }
            bookingScheduleRuleList.add(scheduleRuleVo);
        }
        //可预约日期规则数据
        result.put("bookingScheduleList",bookingScheduleRuleList);
        result.put("total", iPage.getTotal());
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospitalService.getHosNameByHoscode(hoscode));
        //科室
        Department department =departmentService.getDepartment(hoscode, depcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        result.put("baseMap", baseMap);
        return result;
    }

    //根据排班id获取排班详情
    @Override
    public Schedule getById(String scheduleId) {
        Schedule schedule = scheduleRespoitory.findById(scheduleId).get();
        return this.packShudelDetail(schedule);
    }

    //根据排班id获取预约下单数据
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        //通过scheduleId获取schedule
        Schedule schedule = scheduleRespoitory.getScheduleById(scheduleId);
        //Schedule schedule = scheduleMapper.selectById(scheduleId);
        //根据hoscode获取hospital
        Hospital hospital = hospitalService.getHospital(schedule.getHoscode());
        if(hospital == null){
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }
        BookingRule bookingRule = hospital.getBookingRule();
        //把数据设置到scheduleOrderVo
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        scheduleOrderVo.setHoscode(schedule.getHoscode());
        scheduleOrderVo.setHosname(hospitalService.getHosNameByHoscode(schedule.getHoscode()));
        scheduleOrderVo.setDepname(departmentService.getDepName(schedule.getHoscode(),schedule.getDepcode()));
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setAmount(schedule.getAmount());
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setTitle(schedule.getTitle());
        //退号截止天数
        int quitDay = bookingRule.getQuitDay();
        org.joda.time.DateTime quiteTime = getDateTime(new org.joda.time.DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quiteTime.toDate());
        //预约开始时间
        org.joda.time.DateTime startTime = getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        //预约截止时间
        org.joda.time.DateTime endTime = getDateTime(new org.joda.time.DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());
        
        //当天停止挂号时间
        org.joda.time.DateTime  stopTime = getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStopTime(stopTime.toDate());
        return scheduleOrderVo;
    }

    //更新排班信息
    @Override
    public void updateSchedule(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        scheduleRespoitory.save(schedule);
    }

    //拼接时间方法  "2021-07-01" + "08:00" 返回jodaTime类型
    private org.joda.time.DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " "+ timeString;
        org.joda.time.DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }

    //获取可预约的日期数据 根据获取规则里面的 预约周期
    private IPage getListDate(Integer pageNum, Integer pageSize, BookingRule bookingRule) {
        Integer cycle = bookingRule.getCycle();//预约周期
        //拼接时间方法
        String dateTimeString = new org.joda.time.DateTime(new Date()).toString("yyyy-MM-dd") + " " + bookingRule.getReleaseTime();
        //放号时间
        org.joda.time.DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);

        if(dateTime.isBeforeNow()){//如果此日期时间值早于给定的日期时间值，则返回true，否则返回
            cycle+=1;
        }
        //建一个数组放可预约的时间
        List<Date> dateList = new ArrayList<>();
        //获取可预约的所有日期 最后一天为即将放号
        for(int i=0;i<cycle;i++){
            org.joda.time.DateTime plusDays = new org.joda.time.DateTime().plusDays(i);
            String time = plusDays.toString("yyyy-MM-dd");
            dateList.add(new org.joda.time.DateTime(time).toDate());
        }
        //分页核心
        List<Date> pageList = new ArrayList<>();
        int start = (pageNum-1)*pageSize;//点的当前页
        int end = (pageNum-1)*pageSize+pageSize;
        //如果显示数据小于7就直接显示
        if(end<pageList.size()){
            end = pageList.size();
        }
        for(int i=start;i<end;i++){
            pageList.add(dateList.get(i));
        }
        IPage<Date> iPage =
                new com.baomidou.mybatisplus.extension.plugins.pagination.Page<Date>(pageNum,7,dateList.size());
        iPage.setRecords(pageList);
        return iPage;
    }

    //设置编号转成对应的名称
    public Schedule packShudelDetail(Schedule schedule){
        //设置医院名字
        schedule.getParam().put("hosname",hospitalService.getHosNameByHoscode(schedule.getHoscode()));
        //设置科室名称
        schedule.getParam().put("depname",departmentService.getDepName(schedule.getHoscode(),schedule.getDepcode()));
        //设置日期
        schedule.getParam().put("dayOfWeek",dayOfWeek(schedule.getWorkDate()));
        
        return schedule;
    }

    /**
     * 返回星期几
     * @param date
     * @return
     */
    private String dayOfWeek(Date date){
        int day = DateUtil.dayOfWeek(date);
        switch (day){
            case 1:return "星期天";
            case 2:return "星期一";
            case 3:return "星期二";
            case 4:return "星期三";
            case 5:return "星期四";
            case 6:return "星期五";
            case 7:return "星期六";
            default:return "";
        }
    }
}
